# -*- coding: utf-8 -*-

# Define here the models for your spider middleware
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/spider-middleware.html
import scrapy
from scrapy import signals
import urllib.request as req
import re
import requests
import pymysql
import random

class IP:
  def __init__(self):
    #爬取ip的url
    self.url='http://www.89ip.cn/tqdl.html?api=1&num=60&port=&address=&isp='
    #用于测试ip是否可用的url
    self.test_url='https://www.baidu.com/'
    #连接数据库
    self.db=pymysql.connect(host="101.133.166.202",port=3306,user="root",passwd="root",db="stock_analysis",charset='utf8')
    self.cursor=self.db.cursor()
    #每次开启爬虫，都爬取一轮ip
    self.deleteAll()
    self.crawl()
    self.fetch()

  def crawl(self):#爬取ip地址
    #读取网页信息
    page=req.urlopen(self.url)
    data=page.read()
    page.close()
    data=data.decode()
    #提取ip地址
    ips=re.findall('\w*\.\w*\.\w*\.\w*:\w*',data)
    #将得到的ip加入数据库
    self.insert(ips)

  def insert(self,ips):
    #将得到的ip加入数据库
    sql='insert into ip values ("{}")'
    for ip in ips:
      try:
        self.cursor.execute(sql.format(ip))
      except Exception as e:
        continue
    self.cursor.execute('commit')

  def test(self,ip):
    #验证ip是否有用
    proxy_url='https://{}'
    #尝试用该ip连接test_url，成功则返回1，失败则返回0
    try:
      proxy_dict={'http':proxy_url.format(ip)}
      response=requests.get(self.test_url,proxies=proxy_dict)
      #即使连接成功，但连接状态不为200也表示ip有问题
      code=response.status_code
      if code==200:
        return(1)
      else:
        return(0)
    except Exception as e:
      return(0)

  def delete(self,ip):
    #从数据库删掉无用的ip
    sql='delete from ip where `ip`="{}"'.format(ip)
    self.cursor.execute(sql)
    self.cursor.execute('commit')

  def deleteAll(self):
    #清空数据库中ip
    sql='delete from ip'
    self.cursor.execute(sql)
    self.cursor.execute('commit')

  def fetch(self):
    #获取数据库中所有ip
    sql='select `ip` from ip'
    self.cursor.execute(sql)
    #获取数据库中ip
    ips=self.cursor.fetchall()
    self.ips=list(ips)

  def get(self,i=1):
    #从数据库中获取ip并验证，返回第一个可用的ip。i参数用于标记递归终止
    if i>2:#说明此时无论网上还是数据库都无可用ip
      return(None)
    #打乱数组，防止每次都用同一个ip
    random.shuffle(self.ips)
    #验证，决定返回或删除
    for ip in self.ips:
      if self.test(ip[0])==1:
        return(ip[0])
      else:
        self.delete(ip[0])
    #此时数据库中无可用ip，需重新爬取
    self.crawl()
    self.fetch()
    self.get(i+1)

  def close(self):
    #关闭资源
    self.cursor.close()
    self.db.close()


class StockAnalistSpiderMiddleware(object):
    # Not all methods need to be defined. If a method is not defined,
    # scrapy acts as if the spider middleware does not modify the
    # passed objects.

    @classmethod
    def from_crawler(cls, crawler):
        # This method is used by Scrapy to create your spiders.
        s = cls()
        crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
        return s

    def process_spider_input(self, response, spider):
        # Called for each response that goes through the spider
        # middleware and into the spider.

        # Should return None or raise an exception.
        return None

    def process_spider_output(self, response, result, spider):
        # Called with the results returned from the Spider, after
        # it has processed the response.

        # Must return an iterable of Request, dict or Item objects.
        for i in result:
            yield i

    def process_spider_exception(self, response, exception, spider):
        # Called when a spider or process_spider_input() method
        # (from other spider middleware) raises an exception.

        # Should return either None or an iterable of Request, dict
        # or Item objects.
        pass

    def process_start_requests(self, start_requests, spider):
        # Called with the start requests of the spider, and works
        # similarly to the process_spider_output() method, except
        # that it doesn’t have a response associated.

        # Must return only requests (not items).
        for r in start_requests:
            yield r

    def spider_opened(self, spider):
        spider.logger.info('Spider opened: %s' % spider.name)


class StockAnalistDownloaderMiddleware(object):
    # Not all methods need to be defined. If a method is not defined,
    # scrapy acts as if the downloader middleware does not modify the
    # passed objects.
    def __init__(self):
        self.IP=IP()

    @classmethod
    def from_crawler(cls, crawler):
        # This method is used by Scrapy to create your spiders.
        s = cls()
        crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
        return s

    def process_request(self, request, spider):
        # Called for each request that goes through the downloader
        # middleware.

        # Must either:
        # - return None: continue processing this request
        # - or return a Response object
        # - or return a Request object
        # - or raise IgnoreRequest: process_exception() methods of
        #   installed downloader middleware will be called
        if request.meta.get('retry_times'):
            request.meta['REMOTE_ADDR']=('https://'+self.IP.get())
        #print(request.meta['REMOTE_ADDR'])
        return None

    def process_response(self, request, response, spider):
        # Called with the response returned from the downloader.

        # Must either;
        # - return a Response object
        # - return a Request object
        # - or raise IgnoreRequest
        if response.status != 200:
            print('!200')
            request.meta['REMOTE_ADDR']=('https://'+self.IP.get())
            return request
        return response

    def process_exception(self, request, exception, spider):
        # Called when a download handler or a process_request()
        # (from other downloader middleware) raises an exception.

        # Must either:
        # - return None: continue processing this exception
        # - return a Response object: stops process_exception() chain
        # - return a Request object: stops process_exception() chain
        pass

    def spider_opened(self, spider):
        spider.logger.info('Spider opened: %s' % spider.name)

class ProxyMiddleware(object):
    def __init__(self):
        self.IP=IP()

    def process_request(self,request,spider):
        request.meta['proxy']=self.IP.get()
